package org.zjsru.order.web;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import org.zjsru.order.pojo.Order;
import org.zjsru.order.pojo.User;
import org.zjsru.order.service.OrderService;
import com.alibaba.cloud.nacos.discovery.NacosServiceDiscovery;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;
import org.zjsru.order.service.OrderServiceFeign;
import lombok.extern.slf4j.Slf4j;
import org.zjsru.order.task.OrderTimeoutTask;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

   @Autowired
   private OrderService orderService;
    //@Autowired
    //RestTemplate restTemplate ;
    //@Autowired
    //NacosServiceDiscovery serviceDiscovery ;
    @Autowired
    OrderServiceFeign orderServiceFeign ;
    @Autowired
    @Qualifier("org.zjsru.order.web.ProductFeignClient")
    private ProductFeignClient productFeignClient;  // 用于调用商品服务扣减库存
    @Autowired
    private OrderTimeoutTask orderTimeoutTask;




    @RequestMapping(value = "/create", method = {RequestMethod.POST, RequestMethod.GET})
    public String createOrder(
            @RequestParam Long userId,
            @RequestParam Long id,
            @RequestParam Integer num) {

        log.info("接收到创建订单请求：userId={}, productId={}, num={}", userId, id, num);

        try {
            // 1. 先检查并扣减库存
            String deductResult = productFeignClient.deductStock(id, num);
            if (!"库存扣减成功".equals(deductResult)) {
                throw new RuntimeException("库存不足或扣减失败：" + deductResult);
            }
            log.info("库存扣减成功：productId={}, num={}", id, num);

            // 2. 创建订单
            Order order = new Order();
            order.setUserId(userId);
            order.setProductId(id);
            order.setNum(num);
            order.setStatus("未支付"); // 设置初始状态

            Long orderId = orderService.createOrder(order);
            return String.format("订单创建成功，订单ID：%d", orderId);
        } catch (RuntimeException e) {
            log.error("订单创建失败：{}", e.getMessage());
            // 如果库存扣减成功但订单创建失败，需要恢复库存
            try {
                if (e.getMessage().contains("库存扣减成功")) {
                    productFeignClient.deductStock(id, -num); // 负数表示增加库存
                    log.info("已恢复库存：productId={}, num={}", id, num);
                }
            } catch (Exception ex) {
                log.error("恢复库存失败：{}", ex.getMessage());
            }
            return "订单创建失败：" + e.getMessage();
        }
    }

    @GetMapping("/query/{orderId}")
    public Order queryOrderByUserId(@PathVariable("orderId") Long orderId, @RequestHeader("Test") String test) throws NacosException {
        System.out.println(test);
        // 根据id查询订单并返回
        Order order = orderService.queryOrderById(orderId);
        /*ServiceInstance instance = serviceDiscovery.getInstances("user-service").get(0);
        String url = instance.getHost() + ":" + instance.getPort() ;
        User user = restTemplate.getForObject("http://" + url + "/user/" + order.getUserId(), User.class);
        //User user = restTemplate.getForObject("http://user-service/user/" + order.getUserId(), User.class);*/
        User user = orderServiceFeign.queryUserById(order.getUserId());
        order.setUser(user);
        return order;
    }

    @GetMapping("/detail/{orderId}")
    public Order getOrderDetail(@PathVariable("orderId") Long orderId) {
        log.info("接收到查询订单详情请求：orderId={}", orderId);
        return orderService.queryOrderById(orderId);
    }

    @GetMapping("/{orderId}/pay")
    public String updateOrderStatus(@PathVariable("orderId") Long orderId) {
        log.info("接收到更新订单状态请求：orderId={}", orderId);
        try {
            orderService.updateOrderStatus(orderId, "已支付");
            return "订单状态更新成功";
        } catch (Exception e) {
            log.error("订单状态更新失败：{}", e.getMessage());
            return "订单状态更新失败：" + e.getMessage();
        }
    }

    /**
     * 手动触发超时订单检查
     */
    @GetMapping("/check-timeout")
    public String checkTimeoutOrders() {
        log.info("手动触发超时订单检查");
        try {
            orderTimeoutTask.checkTimeoutOrders();
            return "超时订单检查完成";
        } catch (Exception e) {
            log.error("手动触发超时订单检查失败：{}", e.getMessage());
            return "超时订单检查失败：" + e.getMessage();
        }
    }

/*
    @GetMapping("/{userId}")
    public Order findOrderByUserId(@PathVariable("userId") Long userId){
        return null;
    }
*/

}
